package com.bjtime.hprinter.ui

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.*
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.InputType
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import com.bjtime.designer.DataHelper
import com.bjtime.designer.Jutils
import com.bjtime.designer.attributes.ViewAttr
import com.bjtime.designer.utils
import com.bjtime.designer.view.FViewPager
import com.bjtime.designer.widget.*
import com.bjtime.hprinter.Fragments.designer.DesignerPageAdapter
import com.bjtime.hprinter.Fragments.designer.Eles
import com.bjtime.hprinter.Fragments.designer.Sets
import com.bjtime.hprinter.R
import com.bjtime.hprinter.lib.BitmapUtil
import com.bjtime.hprinter.lib.BluetoothConnectActivityReceiver
import com.bjtime.hprinter.lib.ConnectionActivity
import com.puty.sdk.PrinterInstance
import kotlinx.android.synthetic.main.activity_designer.*

//设计界面
class DesignerActivity : AppCompatActivity(), AbsDesignerLayout.onViewSelect,
    Eles.OnEleClickListener, Sets.OnSetClickListener {

    //一些变量的初始化
    companion object {
        //上方画布view
        var mLayout: DesignerLayout? = null
        //下方操作栏的伸缩按钮
        var mExpand: CheckBox? = null
        //右下方的操作界面
        var mPagerView: FViewPager? = null
        //右下方的操作界面的适配器
        var mPagerAdapter: DesignerPageAdapter? = null
        //蓝牙适配器
        var bluetoothAdapter: BluetoothAdapter? = null
        //蓝牙连接的状态广播接收器
        var mReceiver: BroadcastReceiver? = null
        //打印机的name
        var PrintName = ""
        //打印机的mac地址
        var PrintMacAddress = ""
        //设备地址
        var deviceaddress = ""
        //位置权限代号
        val PERMISSION_REQUEST_COARSE_LOCATION = 2
        //代表是否连接
        var connect = true
        //广播接收器
        var receiver: BluetoothConnectActivityReceiver? = null
    }

    //初始的时候的宽高
    var width = 60
    var height = 40

    //下方设置的点击回调
    override fun onSetClick(width: String, height: String) {
        mLayout?.setSize(width.toInt(), height.toInt())
        this.width = width.toInt()
        this.height = height.toInt()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_designer)

        //6.0以上的手机要地理位置权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(
                arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
                PERMISSION_REQUEST_COARSE_LOCATION
            )
        }

        //蓝牙初始化的一些配置
        MainActivitymethod()

        mPagerView = findViewById(R.id.designer_fpv)
        mPagerAdapter = DesignerPageAdapter(supportFragmentManager)
        mPagerView!!.adapter = mPagerAdapter
        mPagerAdapter!!.setOnEleClickListener(this)
        mPagerAdapter!!.setOnSetClickListener(this)

        mLayout = findViewById(R.id.designer_layout)
        mLayout!!.setSelectListener(this)

        mExpand = findViewById(R.id.designer_expan_btn)
        //伸缩按钮的点击 控制下方操作面板是否展示
        mExpand!!.setOnCheckedChangeListener { _, b ->
            if (b)
                designer_expan_layout.visibility = View.VISIBLE
            else
                designer_expan_layout.visibility = View.GONE
        }


        //设置布局中view的点击事件——元素按钮的点击
        radioButton.setOnCheckedChangeListener { _, b ->
            if (b) {
                mPagerView!!.setCurrentItem(0, true)
            }
        }
        //设置布局中view的点击事件——属性按钮的点击
        radioButton2.setOnCheckedChangeListener { _, b ->
            if (b) {
                mPagerView!!.setCurrentItem(1, true)
            }
        }
        //设置布局中view的点击事件——操作按钮的点击 操作按钮已经隐藏了
        radioButton3.setOnCheckedChangeListener { _, b ->
            if (b) {
                mPagerView!!.setCurrentItem(2, true)
            }
        }
        //设置布局中view的点击事件——设置按钮的点击
        radioButton4.setOnCheckedChangeListener { _, b ->
            if (b) {
                mPagerView!!.setCurrentItem(3, true)
            }
        }

        designer_del_btn.setOnClickListener { _ ->
            //先判断有没有选中view
            if (mLayout!!.getCount() == 0 || mLayout!!.getSelectEle() == null)
                Toast.makeText(
                    baseContext,
                    resources.getString(R.string.no_select_ele),
                    Toast.LENGTH_SHORT
                ).show()
            else
                mLayout!!.deleteEle(mLayout!!.getSelectEle()!!, true)
        }

        //缩小按钮的点击
        designer_size_dec.setOnClickListener { _ ->
            //先判断有没有选中view
            if (mLayout!!.getCount() == 0 || mLayout!!.getSelectEle() == null)
                Toast.makeText(
                    baseContext,
                    resources.getString(R.string.no_select_ele),
                    Toast.LENGTH_SHORT
                ).show()
            else if (mLayout!!.getSelectEle() is TextView2) {
                //TextView 减小fontsize
                (mLayout!!.getSelectEle() as TextView2).setTextSize(
                    utils.px2sp(
                        baseContext,
                        (mLayout!!.getSelectEle() as TextView2).getTextSize().toFloat()
                    ) - 2
                )
            } else {
                //获取选中的view 不是TextView的话直接中心改变他的size 达到减小的效果
                val v = mLayout!!.getSelectEle()
                var r = v!!.getRect()
                r.right = r.right - 5
                r.bottom = r.bottom - 5
                mLayout!!.setSize(v, r)
            }
        }

        //放大按钮的点击
        designer_size_add.setOnClickListener { _ ->
            //先判断有没有选中view
            if (mLayout!!.getCount() == 0 || mLayout!!.getSelectEle() == null)
                Toast.makeText(
                    baseContext,
                    resources.getString(R.string.no_select_ele),
                    Toast.LENGTH_SHORT
                ).show()
            else if (mLayout!!.getSelectEle() is TextView2) {
                //TextView 增加fontsize
                (mLayout!!.getSelectEle() as TextView2).setTextSize(
                    utils.px2sp(
                        baseContext,
                        (mLayout!!.getSelectEle() as TextView2).getTextSize().toFloat()
                    ) + 2
                )
            } else {
                //获取选中的view 不是TextView的话直接中心改变他的size 达到变大的效果
                val v = mLayout!!.getSelectEle()
                var r = v!!.getRect()
                r.right = r.right + 5
                r.bottom = r.bottom + 5
                mLayout!!.setSize(v, r)
            }
        }

        //复制按钮的点击
        designer_ele_copy.setOnClickListener { _ ->
            //先判断有没有选中view
            if (mLayout!!.getCount() == 0 || mLayout!!.getSelectEle() == null)
                Toast.makeText(
                    baseContext,
                    resources.getString(R.string.no_select_ele),
                    Toast.LENGTH_SHORT
                ).show()
            else
                //复制当前选中的元素
                mLayout!!.copyEle(mLayout!!.getSelectEle()!!)
        }


        //第一个键盘按钮 点击后image会位于最下层 然后下方变为属性面板
        designer_setcontent_btn.setOnClickListener { _ ->
            radioButton2.performClick()
            //判断原有的所有view 把原先的view当放到上层 相当于image在最下层
            for (item in mLayout!!.getAllLabelView()) {
                if (item is ImageView2) {
                } else {
                    item.bringToFront()
                }
            }
        }


        //因为涉及到一些文件的缓存 需要用到文件读写权限
        PermissionUtils.requestPermission(
            this,
            PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE,
            object : PermissionUtils.PermissionGrant() {
                override fun onPermissionGranted(vararg requestCode: Int) {
                    //每次进入提示权限是否授权
                    Toast.makeText(
                        this@DesignerActivity,
                        "读写权限: " + if (requestCode[0] == -1) "已拒绝" else "已允许",
                        Toast.LENGTH_LONG
                    ).show()
                }
            })
    }

    //蓝牙初始化的一些配置
    fun MainActivitymethod() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Android M Permission check
            //android 6.0 以上 需要授权位置服务 否则搜索不到蓝牙2.0
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                    arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
                    PERMISSION_REQUEST_COARSE_LOCATION
                )
            }
        }
        //注册蓝牙配对广播
        receiver = BluetoothConnectActivityReceiver()
        val filter = IntentFilter()
        filter.addAction("android.bluetooth.device.action.PAIRING_REQUEST")
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED) //状态改变
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
        this.registerReceiver(receiver, filter)
        //注册一个广播用于接收蓝牙配对的回调
        mReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                val action = intent.action
                if (BluetoothDevice.ACTION_FOUND == action) { //得到intent里面的信息
                    val device = intent.getParcelableExtra<BluetoothDevice>(
                        BluetoothDevice.EXTRA_DEVICE
                    )
                        ?: return
                    //判断蓝牙地址是否为空
                    if (device.address == PrintMacAddress && PrintMacAddress !== "") {
                        if (deviceaddress !== "") return
                        bluetoothAdapter!!.cancelDiscovery()
                        deviceaddress =
                            PrintMacAddress
                        val thread =
                            Thread(Runnable {
                                while (PrinterInstance.mPrinter != null) {
                                    PrinterInstance.receiveCallHandler = null
                                }
                                (this@DesignerActivity as Activity).runOnUiThread {
                                    Toast.makeText(
                                        this@DesignerActivity,
                                        "发现设备",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                }
                                val bluetoothDevice: BluetoothDevice =
                                    BluetoothAdapter.getDefaultAdapter()
                                        .getRemoteDevice(PrintMacAddress)
                                PrinterInstance.getPrinterInstance(
                                    bluetoothDevice,
                                    null,
                                    0,
                                    null
                                )
                                connect =
                                    !PrinterInstance.mPrinter.openConnection()
                                if (!connect) {
                                    connect = false
                                    (this@DesignerActivity as Activity).runOnUiThread {
                                        bluetooth.setText(
                                            "已连接：" + PrintName
                                        )
                                    }
                                } else {
                                    bluetoothAdapter!!.cancelDiscovery()
                                    bluetoothAdapter!!.startDiscovery()
                                    PrinterInstance.mPrinter = null
                                    deviceaddress = ""
                                    bluetooth.setText("连接蓝牙")
                                }
                            })
                        thread.start()
                    }
                }
                //断开蓝牙更新图标状态
                if (action == BluetoothDevice.ACTION_ACL_DISCONNECTED) {
                    val device = intent.getParcelableExtra<BluetoothDevice>(
                        BluetoothDevice.EXTRA_DEVICE
                    )
                    if (device == null) {
                        (this@DesignerActivity as Activity).runOnUiThread { bluetooth.setText("已连接：" + PrintName) }
                    }
                }
            }
        }
        val intentFileter = IntentFilter(BluetoothDevice.ACTION_FOUND)
        registerReceiver(mReceiver, intentFileter)
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        //检测蓝牙是否打开
        if (!bluetoothAdapter!!.isEnabled()) {
            val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(intent, 4444)
            //connect=false;
        } else {
            if (bluetoothAdapter != null && PrintMacAddress !== "") {
                bluetoothAdapter!!.cancelDiscovery()
                bluetoothAdapter!!.startDiscovery()
            }
        }
    }


    //每一个view被select时候的回调
    override fun onSelect(v: BaseLabelView?) {
        super.onSelect(v)
        if (v != null) {
            // 特别注意M setSelect方法,不得在create下执行,否则将会给你展示什么叫做 百分百崩溃.
            mPagerAdapter!!.setSelect(v!!.des_viewtype)
            if (mPagerAdapter != null && v != null)
                mPagerAdapter!!.setView(v)

        } else {
            mPagerAdapter!!.setSelect(ViewAttr.VIEW_TYPE.BASE)
        }
    }


    //创建右上角menu的子项目
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        //向menu中添加字体大小的子菜单
        menu.add(0, 1, 0, "搜索蓝牙")
        menu.add(0, 2, 0, resources.getString(R.string.menu_pcode))
        menu.add(0, 3, 0, resources.getString(R.string.menu_save))
        menu.add(0, 4, 0, resources.getString(R.string.menu_open))
        return super.onCreateOptionsMenu(menu)
    }


    override fun onOptionsItemSelected(mi: MenuItem): Boolean {
        //通过ID来判断点击的是哪一个item
        when (mi.itemId) {
            1 -> {
                //跳转到蓝牙配对的界面
                startActivity(Intent(this, ConnectionActivity::class.java))
            }
            2 -> {
                //判断是否已经连接蓝牙
                if (TextUtils.isEmpty(deviceaddress)) {
                    //跳转到蓝牙配对的界面
                    Toast.makeText(this, "请连接蓝牙...", Toast.LENGTH_SHORT)
                    startActivity(Intent(this, ConnectionActivity::class.java))
                } else {
                    //因为打印用的是这个layout的截图 首先取消这个layout中所有view的选中状态
                    for (item in mLayout!!.getAllLabelView()) {
                        item.setSelect(false)
                    }
                    //获取截图
                    mLayout!!.mDesignerLayout!!.isDrawingCacheEnabled = true
                    PrinterInstance.mPrinter.printLabel(
                        BitmapUtil.compress(mLayout!!.mDesignerLayout!!.drawingCache),
                        width, height
                    )
                    //清楚系统中的缓存 必须再次将isDrawingCacheEnabled设置为false
                    mLayout!!.mDesignerLayout!!.isDrawingCacheEnabled = false
                }


            }
            3 -> {
                //取消这个layout中所有view的选中状态
                for (item in mLayout!!.getAllLabelView()) {
                    item.setSelect(false)
                }
                //将所有的信息转换为json 存入本地
                DataHelper.generateJson(mLayout!!, width, height, this, "test")
            }
            4 -> {
                //首先清空整割画板
                mLayout!!.clear()
                //获取上一次本地存储的json
                DataHelper.generateForJson(
                    Jutils.nativeReadHpiFile("/sdcard/fuck.hpi"),
                    mLayout!!
                )
            }
        }
        return true
    }

    //下方控制面板 元素界面的点击回调
    override fun onClickEle(t: ViewAttr.VIEW_TYPE) {
        when (t) {
            //通过不同的type来确定要新增哪一个View
            ViewAttr.VIEW_TYPE.LINE -> {
                //添加Line 线条
                mLayout?.addLabel(ViewAttr.VIEW_TYPE.LINE, "")
            }
            ViewAttr.VIEW_TYPE.IMAGE -> {
                //添加图片 首先先选取图片 在OnActivityResult中回调
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.type = "image/*"
                intent.addCategory(Intent.CATEGORY_OPENABLE)
                startActivityForResult(intent, 6666)
            }
            ViewAttr.VIEW_TYPE.BARCODE -> {
                //添加条形码 先弹窗提示输入的内容
                val et = EditText(this)
                et.inputType=InputType.TYPE_CLASS_NUMBER
                android.app.AlertDialog.Builder(this).apply {
                    setTitle("请输入条形码内容")
                        .setView(et)
                    setPositiveButton("确定", DialogInterface.OnClickListener { _, _ ->
                        mLayout?.addLabel(ViewAttr.VIEW_TYPE.BARCODE, et.text.toString())
                    })
                        .setNegativeButton("取消", DialogInterface.OnClickListener { _, _ -> })
                    show()
                }
            }
            ViewAttr.VIEW_TYPE.QRCODE -> {
                //添加二维码 先弹窗提示输入的内容
                val et = EditText(this)
                android.app.AlertDialog.Builder(this).apply {
                    setTitle("请输入二维码内容")
                        .setView(et)
                    setPositiveButton("确定", DialogInterface.OnClickListener { _, _ ->
                        mLayout?.addLabel(ViewAttr.VIEW_TYPE.QRCODE, et.text.toString())
                    })
                        .setNegativeButton("取消", DialogInterface.OnClickListener { _, _ -> })
                    show()
                }
            }
            ViewAttr.VIEW_TYPE.TEXT -> {
                //添加文本内容 先弹窗提示输入的内容
                val et = EditText(this)
                android.app.AlertDialog.Builder(this).apply {
                    setTitle("请输入文本内容")
                        .setView(et)
                    setPositiveButton("确定", DialogInterface.OnClickListener { _, _ ->
                        mLayout?.addLabel(ViewAttr.VIEW_TYPE.TEXT, et.text.toString())
                    })
                        .setNegativeButton("取消", DialogInterface.OnClickListener { _, _ -> })
                    show()
                }

            }
        }
    }

    //选取图片的回调
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //判断code是不是选取图片
        if (requestCode == 6666) {
            if (data!=null&&data.data != null) {
                //获取选中的图片的路径
                var path = com.bjtime.hprinter.utils.getPath(this!!, data!!.data)
                //添加一个image
                mLayout?.addLabel(ViewAttr.VIEW_TYPE.IMAGE, path!!)
                //当插入一个新的view的时候 判断原有的所有view 把原先的view当放到上层 相当于image在最下层
                for (item in mLayout!!.getAllLabelView()) {
                    if (item is ImageView2) {
                    } else {
                        item.bringToFront()
                    }
                }
            }


        }
    }
}
